<script setup lang="ts">
import { ref } from 'vue';

import { useVbenModal, z } from '@vben/common-ui';

import { message } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';
import {
  dictItemAddApi,
  dictItemEditApi,
  dictItemQueryByIdApi,
} from '#/api/system/dictItem';
import { queryDictOptionsApi } from '#/utils';
import { asyncValidDataApi } from '#/utils/handle/async-rules';

const record = ref({});
const dictId = ref();
const presupposeColors = ref([
  // pre:状态，none: 纯颜色
  { type: 'pre', color: 'default' },
  { type: 'pre', color: 'success' },
  { type: 'pre', color: 'error' },
  { type: 'pre', color: 'processing' },
  { type: 'pre', color: 'warning' },
  { type: 'none', color: 'orange' },
  { type: 'none', color: 'cyan' },
  { type: 'none', color: 'purple' },
]);

const colors = ref([
  // pre:带图标，none:无图标
  // { type: 'pre', color: 'success' },
  // { type: 'pre', color: 'processing' },
  // { type: 'pre', color: 'error' },
  // { type: 'pre', color: 'warning' },
  // { type: 'pre', color: 'default' },
  { type: 'none', color: 'default' },
  { type: 'none', color: 'success' },
  { type: 'none', color: 'error' },
  { type: 'none', color: 'processing' },
  { type: 'none', color: 'warning' },
  { type: 'none', color: 'pink' },
  { type: 'none', color: 'red' },
  { type: 'none', color: 'orange' },
  { type: 'none', color: 'green' },
  { type: 'none', color: 'blue' },
  { type: 'none', color: 'cyan' },
  { type: 'none', color: 'purple' },
]);

const [Form, formApi] = useVbenForm({
  showDefaultActions: false,
  wrapperClass: 'grid-cols-2',
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
  },
  schema: [
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入字典项文本',
      },
      fieldName: 'itemText',
      label: '字典项文本',
      rules: z.string().max(30, '字典项文本最多30个字符'),
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入字典项值',
      },
      fieldName: 'itemVal',
      label: '字典项值',
      dependencies: {
        // 实现异步API校验
        rules(values, formApi) {
          const rowId = formApi.values?.id;
          return asyncValidDataApi(
            z.string({ required_error: '请输入字典项值' }),
            {
              tableName: 'sys_dict_item',
              fieldName: 'item_val',
              rowId,
              sqlSelect: `del_flag = 0 and dict_id = '${dictId.value}'`,
            },
          );
        },
        triggerFields: ['itemVal'],
      },
    },
    {
      component: 'InputNumber',
      componentProps: {
        placeholder: '请输入排序',
      },
      fieldName: 'sortRank',
      label: '排序',
    },
    {
      component: 'ApiRadioGroup',
      defaultValue: 0,
      rules: 'required',
      componentProps: {
        buttonStyle: 'solid',
        optionType: 'button',
        afterFetch: (data) => {
          return data.map((item: any) => ({
            label: item.itemText,
            value: Number.parseInt(item.itemVal),
          }));
        },
        api: queryDictOptionsApi,
        params: {
          dictCode: 'status',
        },
      },
      fieldName: 'status',
      label: '状态',
    },
    {
      component: 'RadioGroup',
      defaultValue: 0,
      rules: 'required',
      componentProps: {
        buttonStyle: 'solid',
        optionType: 'button',
        options: [
          {
            label: '无',
            value: 0,
          },
          {
            label: '徽标',
            value: 1,
          },
          {
            label: '标签',
            value: 2,
          },
        ],
      },
      formItemClass: 'col-span-2 items-baseline',
      fieldName: 'showStyle',
      label: '展示样式',
    },
    {
      component: 'RadioGroup',
      defaultValue: 'default',
      rules: 'required',
      componentProps: {
        index: 1,
        placeholder: '请输入展示样式颜色',
        buttonStyle: 'solid',
        optionType: 'button',
      },
      fieldName: 'showStyleColor',
      label: '展示样式颜色',
      dependencies: {
        show(values) {
          return values.showStyle === 1;
        },
        triggerFields: ['showStyle'],
      },
      formItemClass: 'col-span-2 items-baseline',
    },
    {
      component: 'RadioGroup',
      defaultValue: 'pink',
      rules: 'required',
      componentProps: {
        index: 2,
      },
      fieldName: 'showStyleColor',
      label: '展示样式颜色',
      dependencies: {
        show(values) {
          return values.showStyle === 2;
        },
        triggerFields: ['showStyle'],
      },
      formItemClass: 'col-span-2 items-baseline',
    },
    // {
    //   component: 'Input',
    //   rules: 'required',
    //   componentProps: {
    //     placeholder: '请输入展示样式颜色',
    //   },
    //   fieldName: 'showStyleColor',
    //   label: '展示样式颜色',
    //   dependencies: {
    //     show(values) {
    //       return values.showStyle !== 0;
    //     },
    //     triggerFields: ['showStyle'],
    //   },
    // },
    {
      component: 'Textarea',
      componentProps: {
        placeholder: '请输入备注',
      },
      formItemClass: 'col-span-2 items-baseline',
      fieldName: 'remark',
      label: '备注',
    },
  ],
});
const [DictItemModal, modalApi] = useVbenModal({
  title: '字典项',
  onCancel: () => {
    modalApi.close();
  },
  onConfirm: onSubmit,
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      record.value = modalApi.getData<Record<string, any>>();
      modalApi.setState({
        title: `${record.value.id ? '编辑' : '新增'}字典项`,
      });
      if (record.value.id) {
        initFun();
      } else {
        dictId.value = record.value?.dictId;
        formApi.setValues(record.value, false);
      }
    }
  },
});

async function initFun() {
  const res = await dictItemQueryByIdApi({ id: record.value.id });
  dictId.value = res?.dictId;
  await formApi.setValues(res, false);
}

async function onSubmit() {
  const { valid } = await formApi.validate();
  const values = await formApi.getValues();
  if (valid) {
    if (record.value.id) {
      const msg = await dictItemEditApi(values);
      message.success(msg);
      await modalApi.close();
    } else {
      const msg = await dictItemAddApi(values);
      message.success(msg);
      await modalApi.close();
    }
  }
}
</script>

<template>
  <DictItemModal>
    <Form>
      <template #showStyleColor="slotProps">
        <a-radio-group
          v-if="slotProps.index === 1"
          v-bind="slotProps"
          name="radioGroup"
        >
          <a-radio
            v-for="(item, index) in presupposeColors"
            :key="index"
            :value="item.color"
          >
            <a-badge v-if="item.type === 'pre'" :status="item.color" />
            <a-badge v-else :color="item.color" />
          </a-radio>
        </a-radio-group>
        <a-radio-group
          v-if="slotProps.index === 2"
          v-bind="slotProps"
          name="radioGroup"
        >
          <a-radio
            v-for="(item, index) in colors"
            :key="index"
            class="mb-2"
            :value="item.color"
          >
            <a-tag :color="item.color">
              <template v-if="item.type === 'pre'" #icon>
                <span class="icon-[ant-design--check-circle-outlined]"></span>
              </template>
              {{ item.color }}
            </a-tag>
          </a-radio>
        </a-radio-group>
      </template>
    </Form>
  </DictItemModal>
</template>
